package nero.yncc.com.createart.base;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.annotation.StringDef;
import android.support.v4.app.FragmentActivity;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.readystatesoftware.systembartint.SystemBarTintManager;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import nero.yncc.com.createart.R;
import nero.yncc.com.createart.activity.ActicityLogin;
import nero.yncc.com.createart.bean.UserBean;
import nero.yncc.com.createart.custom.IconView;
import nero.yncc.com.createart.custom.ListVIewScroll;
import nero.yncc.com.createart.utils.DialogUtil;
import nero.yncc.com.createart.utils.SomeUtil;
import nero.yncc.com.createart.utils.TimeUtils;
import nero.yncc.com.createart.utils.UserDataUtil;

/**
 * Created by nero on 17-6-19.
 * activity基类
 */

public class BaseActivity extends FragmentActivity implements View.OnClickListener {
    @ViewInject(R.id.tv_titlebat_title)
    TextView tv_titlebat_title;
    @ViewInject(R.id.ll_titlebar)
    LinearLayout ll_titlebar;   //titlebar的父容器 用于动态增加scrollview
    @ViewInject(R.id.tv_title_right)
     protected TextView tv_title_right;
    @ViewInject(R.id.icon_back_title)
    IconView icon_back_title;
    @ViewInject(R.id.icon_state_where)
    IconView icon_state_where;
    @ViewInject(R.id.icon_network)
    IconView icon_network;
    @ViewInject(R.id.icon_location)
    IconView icon_location;
    @ViewInject(R.id.tv_battery)
    TextView tv_battery;
    @ViewInject(R.id.icon_battery)
    IconView icon_battery;

    @ViewInject(R.id.tv_state_time)  //状态栏的时间
            TextView tv_state_time;

    SystemBarTintManager tintManager;
    protected UserBean userBean;

    protected ListVIewScroll scrollView; //包裹的scrollvview 单独写出来是因为可以设置冲突的listview进去
    protected Context mContext;
    boolean canClose = false;

    protected int screenHeight;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        mContext = this;
        userBean = UserDataUtil.getUserData(mContext);
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        screenHeight = metrics.heightPixels;


//        initStateBar();
//        setStateBarColor(R.color.statebar_black);

        initView();
        setState();
        initData();
        initListener();
        getHttpData();
        Log.e("123", SomeUtil.getRunningActivityName());

    }

//    @TargetApi(19)
//    private void setTranslucentStatus(boolean on) {
//        Window win = getWindow();
//        WindowManager.LayoutParams winParams = win.getAttributes();
//        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
//        if (on) {
//            winParams.flags |= bits;
//        } else {
//            winParams.flags &= ~bits;
//        }
//        win.setAttributes(winParams);
//    }

    @Override
    public void onClick(View view) {
        doClick(view.getId());
    }


    /**
     * 初始化数据
     */
    protected void initData() {

    }

    /**
     * 初始化view
     */
    protected void initView() {

    }

    /**
     * 初始化监听器
     */
    protected void initListener() {
        if (icon_back_title != null)
            icon_back_title.setOnClickListener(this);
    }

    /**
     * 网络请求自动
     */
    protected void getHttpData() {

    }

    /**
     * 网络请求手动
     */
    protected void getData() {

    }


    //关闭软键盘
    protected void closeSoftware() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive() && getCurrentFocus() != null) {
            if (getCurrentFocus().getWindowToken() != null) {
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }


    /**
     * 是否需要被scrollview包围 调用此方法后将自动给当前窗体所有增加一个scrollview
     * 如果需要将标题栏排除在外面 传false
     *
     * @param containTitle 是否包含标题栏
     */
    protected void byScroll(boolean containTitle) {

        if (containTitle) {
            View view_root = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
            scrollView = new ListVIewScroll(this);
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(-1, -1);
            scrollView.setLayoutParams(params);

            this.setContentView(scrollView);
            scrollView.addView(view_root);
        } else {

            ViewGroup viewGroup_root = findViewById(android.R.id.content);
            ViewGroup view_root = (ViewGroup) viewGroup_root.getChildAt(0);

            //初始化scrollview
            ScrollView scrollView = new ScrollView(this);
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(-1, -1);
            scrollView.setLayoutParams(params);

            //初始化scrollview的父view 并增加进scrollview
            LinearLayout linearLayout_root = new LinearLayout(mContext);
            linearLayout_root.setLayoutParams(params);

            this.setContentView(linearLayout_root);

            view_root.removeView(ll_titlebar);//先移除
            linearLayout_root.addView(ll_titlebar);
            linearLayout_root.addView(scrollView);
            linearLayout_root.setOrientation(LinearLayout.VERTICAL);

            showLog(view_root.getChildCount() + "");
            view_root.setLayoutParams(params);
            scrollView.addView(view_root);
        }

    }

    /**
     * 是否需要被scrollview包围 调用此方法后将自动给当前窗体所有增加一个scrollview
     * 如果需要将标题栏排除在外面 传false
     *
     * @param containTitle 是否包含标题栏
     */
    protected void byScrollRefresh(boolean containTitle) {

        if (containTitle) {
            View view_root = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
            scrollView = new ListVIewScroll(this);
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(-1, -1);
            scrollView.setLayoutParams(params);

            this.setContentView(scrollView);
            scrollView.addView(view_root);
        } else {

            ViewGroup viewGroup_root = findViewById(android.R.id.content);
            ViewGroup view_root = (ViewGroup) viewGroup_root.getChildAt(0);

            //初始化scrollview
            ScrollView scrollView = new ScrollView(this);
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(-1, -1);
            scrollView.setLayoutParams(params);

            //初始化scrollview的父view 并增加进scrollview
            LinearLayout linearLayout_root = new LinearLayout(mContext);
            linearLayout_root.setLayoutParams(params);

            this.setContentView(linearLayout_root);

            view_root.removeView(ll_titlebar);//先移除
            //添加刷新布局
            View viewRefresh = LinearLayout.inflate(mContext, R.layout.refresh_top, null);
            linearLayout_root.addView(viewRefresh);

            linearLayout_root.addView(ll_titlebar);
            linearLayout_root.addView(scrollView);
            linearLayout_root.setOrientation(LinearLayout.VERTICAL);

            view_root.setLayoutParams(params);
            scrollView.addView(view_root);
        }

    }

    protected void showLog(String msg) {
        Log.e("123", msg);
    }

//    /**
//     * 获取状态栏高度 主要用于沉浸式自动顶出高度padding 在不设置颜色的时候需要
//     */
//    protected int getStateBarHeight() {
//        int statusBarHeight1 = -1;
////获取status_bar_height资源的ID
//        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
//        if (resourceId > 0) {
//            //根据资源ID获取响应的尺寸值
//            statusBarHeight1 = getResources().getDimensionPixelSize(resourceId);
//        }
//        return statusBarHeight1;
//    }
//
//    /**
//     * 初始化状态栏
//     */
//    private void initStateBar() {
//        //初始化状态栏
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            setTranslucentStatus(true);
//        }
//        tintManager = new SystemBarTintManager(this);
//        tintManager.setStatusBarTintEnabled(true);
//        tintManager.setStatusBarTintResource(R.color.translate);//通知栏所需颜色
//    }

    /**
     * 点击事件监听封装
     */
    protected void doClick(int id) {
        switch (id) {
            case R.id.icon_back_title:
                finish();
                break;
        }
    }

    /**
     * 设置标题栏标题
     *
     * @param title 标题文本
     */
    protected void setTitleBarTitle(String title) {
        if (tv_titlebat_title != null && title != null)
            tv_titlebat_title.setText(title);
    }

    /**
     * 设置状态栏颜色
     *
     * @param colorResId 颜色ID值
     */
    protected void setStateBarColor(int colorResId) {
//        tintManager.setStatusBarTintResource(colorResId);//通知栏所需颜色
    }

    /**
     * 提示吐司 短时间
     *
     * @param msg 显示的内容
     */
    protected void showToast(String msg) {
        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
    }


    /**
     * 提示吐司 短时间长时间
     *
     * @param msg    显示的内容
     * @param islong 是否长时间 true为长时间
     */
    protected void showToast(String msg, boolean islong) {
        if (islong) {
            Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
        }
    }


    ProgressDialog progressDialog;

    /**
     * 展示进度条
     */
    protected void showProgress() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(mContext);
            progressDialog.setCancelable(false);
        }
        if (progressDialog.isShowing()) return;
        progressDialog.setMessage("正在加载。。。");
        progressDialog.show();
    }

    /**
     * 展示进度条
     */
    protected void showProgress(String msg) {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(mContext);
            progressDialog.setCancelable(false);
        }

        if (progressDialog.isShowing()) return;
        progressDialog.setMessage(msg);
        progressDialog.show();
    }

    /**
     * 隐藏进度条
     */
    protected void hideProgress() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    /**
     * 判断是不是在个人中心界面点击返回按钮 判断两次点击退出
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (SomeUtil.getRunningActivityName().indexOf("ActivityPerCenter") > -1) {
                if (canClose) {
//                    cleanAliasYo();
                } else {
                    canClose = true;
                    showToast("再按一次退出程序");
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            canClose = false;
                        }
                    }, 1000);
                }
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 设置标题栏右边的东西
     */
    protected void setRight(String text, View.OnClickListener listener) {
        tv_title_right.setText(text);
        tv_title_right.setOnClickListener(listener);
        tv_title_right.setVisibility(View.VISIBLE);
    }

    /**
     * 初始化pulltorefreshlistview属性
     */
    protected void setPullToRefreshListView(PullToRefreshListView pullToRefreshListView) {
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        pullToRefreshListView.getLoadingLayoutProxy(false, true).setPullLabel(getString(R.string.pull_to_up_loading_msg));
        pullToRefreshListView.getLoadingLayoutProxy(false, true).setReleaseLabel(getString(R.string.pull_to_up_releasing_msg));
    }

    protected void exitLogin() {
        UserDataUtil.delUserData(this);
        Intent intent = new Intent(mContext, ActicityLogin.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    /**
     * 设置模仿状态栏的状态
     */
    private void setState() {
        if (icon_network == null)
            return;
        //设置时间 一分钟执行一次
        if (tv_state_time != null) {
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tv_state_time.setText(TimeUtils.getTimeShort(new Date()));
                        }
                    });

                }
            }, 0, 60000);
        }
        //设置网络制式
//        TelephonyManager telMgr = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
//        String IMSI; // 返回唯一的用户ID;就是这张卡的编号神马的
//        IMSI = telMgr.getSubscriberId();
//        // IMSI号前面3位460是国家，紧接着后面2位00 02是中国移动，01是中国联通，03是中国电信。其中
//        if (IMSI == null)
//            icon_state_where.setText(R.string.icon_yidong);
//        if (IMSI.startsWith("46000") || IMSI.startsWith("46002")) {
//            icon_state_where.setText(R.string.icon_yidong);
//        } else if (IMSI.startsWith("46001")) {
//            icon_state_where.setText(R.string.icon_liantong);
//        } else if (IMSI.startsWith("46003")) {
//            icon_state_where.setText(R.string.icon_dianxin);
//
//        }
        TelephonyManager telManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

        String operator = telManager.getSimOperator();
        if (operator != null) {
            if (operator.equals("46000") || operator.equals("46002")) {
                icon_state_where.setText(R.string.icon_yidong);
            } else if (operator.equals("46001")) {
                icon_state_where.setText(R.string.icon_liantong);
            } else if (operator.equals("46003")) {
                icon_state_where.setText(R.string.icon_dianxin);
            }
        } else {
            icon_state_where.setText(R.string.icon_yidong);
        }

        //获取网络类型
        getNetWorkStatus(mContext);

        //获取GPS是否开启
        if (isOPen(mContext)) {
            icon_location.setVisibility(View.VISIBLE);
        } else {
            icon_location.setVisibility(View.GONE);
        }
        icon_battery.setTextColor(getResources().getColor(R.color.textColorGray));
        //设置电量
        if (Constants.battery > 90) {
            icon_battery.setText(R.string.icon_power_100);
        } else if (Constants.battery <= 90 && Constants.battery > 60) {
            icon_battery.setText(R.string.icon_power_75);
        } else if (Constants.battery <= 60 && Constants.battery > 35) {
            icon_battery.setText(R.string.icon_power_50);
        } else if (Constants.battery <= 35 && Constants.battery > 15) {
            icon_battery.setText(R.string.icon_power_25);
        } else if (Constants.battery <= 15 && Constants.battery > 0) {
            icon_battery.setText(R.string.icon_power_10);
            icon_battery.setTextColor(getResources().getColor(R.color.project_red));
        }
        tv_battery.setText(Constants.battery + "%");
    }



    public int getNetWorkStatus(Context context) {
        int netWorkType = Constants.NETWORK_CLASS_UNKNOWN;

        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

        if (networkInfo != null && networkInfo.isConnected()) {
            int type = networkInfo.getType();

            if (type == ConnectivityManager.TYPE_WIFI) {
                icon_network.setText(R.string.icon_wifi);
            } else if (type == ConnectivityManager.TYPE_MOBILE) {
                icon_network.setText(R.string.icon_4g);
            } else {
                icon_network.setText(R.string.icon_wifi);
            }
        }

        return netWorkType;
    }

    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     *
     * @param context
     * @return true 表示开启
     */
    public final boolean isOPen(final Context context) {
        LocationManager locationManager
                = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }

        return false;
    }
}
